/*
 * Copyright 2009 Alberto Gimeno <gimenete at gmail.com>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package siena.remote;

import java.io.IOException;
import java.util.Properties;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import siena.PersistenceManager;
import siena.Query;
import siena.SienaException;
import siena.Util;

public class RemotePersistenceManager implements PersistenceManager {
	
	private Connector connector;
	private Serializer serializer;
	private String key;

	public void init(Properties p) {
		String connectorImpl = p.getProperty("connector");
		if(connectorImpl != null) {
			try {
				connector = (Connector) Class.forName(connectorImpl).newInstance();
			} catch (Exception e) {
				throw new SienaException("Error while instantiating connector: "+connectorImpl, e);
			}
		} else {
			connector = new URLConnector();
		}
		
		String serializerImpl = p.getProperty("serializer");
		if(serializerImpl != null) {
			try {
				serializer = (Serializer) Class.forName(serializerImpl).newInstance();
			} catch (Exception e) {
				throw new SienaException("Error while instantiating serializer: "+serializerImpl, e);
			}
		} else {
			serializer = new XmlSerializer();
		}
		
		key = p.getProperty("key");
		
		connector.configure(p);
	}

	public <T> Query<T> createQuery(Class<T> clazz) {
		return new RemoteQuery<T>(this, clazz);
	}

	public void delete(Object obj) {
		simpleRequest("delete", obj, true);
	}

	public void get(Object obj) {
		simpleRequest("get", obj, true);
	}

	public void insert(Object obj) {
		simpleRequest("insert", obj, false);
	}

	public void update(Object obj) {
		simpleRequest("update", obj, false);
	}
	
	protected Document createRequest(String name) {
		Document d = DocumentHelper.createDocument();
		Element root = d.addElement(name);
		if(key != null) {
			String time = Long.toString(System.currentTimeMillis());
			root.addAttribute("time", time);
			root.addAttribute("hash", Util.sha1(time+key));
		}
		return d;
	}
	
	private Document createRequest(String name, Object entity, boolean ids) {
		Document d = createRequest(name);
		Common.fillRequestElement(entity, d.getRootElement(), ids);
		return d;
	}
	
	private void simpleRequest(String name, Object entity, boolean ids) {
		Document request = createRequest(name, entity, ids);
		Document response = send(request);
		Element root = response.getRootElement();
		String rootName = root.getName();
		if("error".equals(rootName)) {
			throw new SienaException(root.attributeValue("class") + " " +root.getText());
		}
		if("object".equals(rootName)) {
			Common.parseEntity(entity, root, entity.getClass().getClassLoader());
		}
	}
	
	protected Document send(Document request) {
		try {
			connector.connect();
			serializer.serialize(request, connector.getOutputStream());
			Document response = serializer.deserialize(connector.getInputStream());
			connector.close();
			return response;
		} catch(IOException e) {
			throw new SienaException(e);
		}
	}

	public void rollbackTransaction() {
	}

	public void beginTransaction(int isolationLevel) {
	}

	public void closeConnection() {
	}

	public void commitTransaction() {
	}
	
}
